<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use EasyWeChat\Foundation\Application;
use think\Config;

class Item extends Frontend
{

    protected $layout = 'spread';

    /**
     * Itemtimes模型对象
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Itemtimes');
    }

    public function view()
    {
        $qrcode = $this->request->get("qrcode", '0');

        //echo $qrcode;

        //$row = $this->model->get($qrcode);
        //dump($row);

      //  $app = new Application($config);
        $app = new Application(Config::get('wechat'));
        $oauth = $app->oauth;

        // 未登录
       if (empty(session('wechat_user'))) {
           session('target_url','/index/item/view?qrcode='.$qrcode);
            return $oauth->redirect();
            // 这里不一定是return，如果你的框架action不是返回内容的话你就得使用
            // $oauth->redirect()->send();
        }
// 已经登录过
        $user = session('wechat_user');
// ...

//        dump($user);

        $where['qrcodecode'] = $qrcode;
        $where['openid'] = $user['id'];

        $item = $this->model->where($where)->find();

        if(empty($item)){
            $params['qrcodecode']=$qrcode;
            $params['openid']=$user['id'];
            $params['headimage']=$user['avatar'];
            $params['nickname']=$user['nickname'];
            $params['viewtimes']=1;

            $this->model->save($params);
        }else{
            //dump($item);
            //$item->viewtimes += 1;
            $this->model->where($where)->setInc('viewtimes',1);
        }


//        dump($params);



        return $this->view->fetch();
    }

}
